<script setup>
import request from "@/utils/request";
import { reactive, ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'

// 数据模型
const data = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  tableData: [],
  name: '',
  loading: false
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

const formRef = ref(null)

// 加载用户列表
const loadUsers = async () => {
  data.loading = true;
  try {
    const res = await request.get('/users/page', {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        name: data.name
      }
    });
    
    if (res.code === 200) {
      data.tableData = res.data.records;
      data.total = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    data.loading = false;
  }
}

// 新增用户
const handleAdd = () => {
  data.form = {
    username: '',
    password: '',
    email: '',
    role: 'USER'
  };
  data.formVisible = true;
}

// 编辑用户
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify({
    id: row.id,
    username: row.username,
    email: row.email,
    role: row.role
  }));
  data.formVisible = true;
}

// 保存用户
const handleSave = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    const isEdit = data.form.id;
    const result = await request[isEdit ? 'put' : 'post'](
      isEdit ? '/users/update' : '/users/add',
      data.form
    );

    if (result.code === 200) {
      ElMessage.success(isEdit ? '修改成功' : '添加成功');
      data.formVisible = false;
      loadUsers();
    } else {
      ElMessage.error(result.msg || (isEdit ? '修改失败' : '添加失败'));
    }
  } catch (error) {
    console.error('保存用户失败:', error);
    ElMessage.error('保存失败');
  }
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该用户吗？此操作不可恢复',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const result = await request.delete('/users/' + row.id);
      if (result.code === 200) {
        ElMessage.success('删除成功');
        // 如果当前页只有一条数据，删除后跳转到上一页
        if (data.tableData.length === 1 && data.pageNum > 1) {
          data.pageNum--;
        }
        loadUsers();
      } else {
        ElMessage.error(result.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 重置搜索
const handleReset = () => {
  data.name = '';
  data.pageNum = 1;
  loadUsers();
}

// 页码改变
const handleCurrentChange = (val) => {
  data.pageNum = val;
  loadUsers();
}

// 每页条数改变
const handleSizeChange = (val) => {
  data.pageSize = val;
  data.pageNum = 1;
  loadUsers();
}

// 初始加载
onMounted(() => {
  loadUsers();
})
</script>

<template>
  <div class="admin-container">
    <el-card class="search-card">
      <div class="search-area">
        <el-input
          v-model="data.name"
          placeholder="请输入用户名搜索"
          clearable
          @keyup.enter="loadUsers"
          style="width: 200px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <div class="button-group">
          <el-button type="primary" :icon="Search" @click="loadUsers">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Plus" @click="handleAdd">新增用户</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="table-card">
      <el-table 
        :data="data.tableData" 
        stripe 
        border 
        v-loading="data.loading"
        style="width: 100%"
      >
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'ADMIN' ? 'danger' : 'success'">
              {{ row.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              :icon="Edit" 
              circle
              @click="handleEdit(row)"
            />
            <el-button 
              type="danger" 
              :icon="Delete" 
              circle
              @click="handleDelete(row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog 
      :title="data.form.id ? '编辑用户' : '新增用户'" 
      v-model="data.formVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="data.form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="data.form.username" 
            placeholder="请输入用户名(5-16位)"
            :disabled="!!data.form.id"
          />
        </el-form-item>
        <el-form-item 
          label="密码" 
          prop="password"
          v-if="!data.form.id"
        >
          <el-input 
            v-model="data.form.password" 
            type="password" 
            show-password
            placeholder="请输入密码(5-16位)"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="data.form.email" 
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="data.form.role" placeholder="请选择角色">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.admin-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
    
    .search-area {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .button-group {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

:deep(.el-tag) {
  width: 80px;
  text-align: center;
}
</style>